﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using UnityCore;
using System.Data;
using System.Data.Odbc;
using StoreClientModule;
using DataManager;

namespace DataManager
{
    //--------------------------------
    //            structs
    //--------------------------------
    public struct SearchInfo
    {
        public string keyword;
        public int start;
    } //end 
    public struct ProfileInfo
    {
        public string referenceNumber;
        public string name;
        public string address;
        public string contactNumber;
        public DateTime date;
        public string status;

        public string uniqueName;

        public string SalesReferenceNumber;
        public string ChargeReferenceNumber;
    } // end struct ProfileInfo
    
    public struct chargeMigrate
    {
        public string invoiceNumber;
        public string balance;
    }

    //--------------------------------
    //     class CommonConnection
    //--------------------------------
    static class CommonConnection
    {
        public static OdbcDetails od = new OdbcDetails() { VER = OdbcVersion.v510, SVR = Common.lServer, UID = Common.lUID, PWD = Common.lPWD, DB = Common.lDatabase, TIMEOUT = 5 };
        public static OdbcDetails od_online = new OdbcDetails() { VER = OdbcVersion.v510, SVR = Common.oServer, UID = Common.oUID, PWD = Common.oPWD, DB = Common.oDatabase, TIMEOUT = 5 };


    } // end class CommonConnection

    //--------------------------------
    //     class ProfileManager
    //--------------------------------
    public class ProfileManager
    {
        // field
        OdbcAccess db = new OdbcAccess(CommonConnection.od);
        string salesReferenceNumber = null;
        string chargeReferenceNumber = null;

        string salesCode = "A";
        string chargeCode = "B";
        public string count = "";

        public DataTable exportTable = new DataTable();
        // constructor
        public ProfileManager() { }

        //sync operation methods
        void pAutoRef(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "AutoRef" };
            int cnt = 0;
            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();

                db.Query("SELECT * FROM tblReferenceNumber");
                int num = int.Parse(db.GetField(0, "fBuffer").ToString());
                string stamp = db.GetField(0, "fStamp").ToString();

                int recCnt = num;
                num++;
                count = "" + recCnt;
                db.Query("SELECT * FROM tblReferenceNumber");
                if (stamp == db.GetField(0, "fStamp").ToString())
                {
                    db.SetField(0, "fBuffer", num.ToString());
                    db.Commit(ConflictOption.CompareRowVersion);

                    //create reference number
                    cnt = recCnt % 1000;

                    int i = (int)recCnt / 1000;
                    for (int j = 1; j <= i; j++)
                    {
                        salesCode += "A";
                        chargeCode += "B";
                    }

                    if (cnt == 0)
                    {
                        db.Query("SELECT * FROM tblReferenceNumber");
                        db.SetField(0, "fBuffer", (recCnt + 2).ToString());
                        db.Commit(ConflictOption.CompareRowVersion);
                        cnt++;
                    }

                    salesReferenceNumber = salesCode + "" + (double.Parse(Common.lStoreID) + cnt);
                    chargeReferenceNumber = chargeCode + "" + (double.Parse(Common.lStoreID) + cnt);
                }
                else
                {
                    proc.HasError = true;
                    proc.Msg = "Reference number already used. Please generate another.";
                }



                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        } // end pAutoRef

        void pGetCancelledRef(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "GetCancelledRef" };
            int refNum = 0;
            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                db.Query("SELECT * FROM tblReferenceNumberCancelled ORDER BY fID ASC");
                if (db.Count > 0)
                {
                    refNum = int.Parse(db.GetField(0, "fReferenceNumber").ToString());
                    db.Delete(0);
                    db.Commit();

                    //create reference number
                    int recCnt = refNum;

                    int cnt = recCnt % 1000;

                    int i = (int)recCnt / 1000;
                    for (int j = 1; j <= i; j++)
                    {
                        salesCode += "A";
                        chargeCode += "B";
                    }

                    if (cnt == 0)
                    {
                        db.Query("SELECT * FROM tblReferenceNumber");
                        db.SetField(0, "fBuffer", (recCnt + 2).ToString());
                        db.Commit(ConflictOption.CompareRowVersion);
                        cnt++;
                    }

                    salesReferenceNumber = salesCode + "" + (double.Parse(Common.lStoreID) + cnt);
                    chargeReferenceNumber = chargeCode + "" + (double.Parse(Common.lStoreID) + cnt);

                    count = "" + refNum;
                }
                else
                {
                    proc.HasError = true;
                }

                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }

        }

        void pSaveCancelledRef(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "SaveCancelledRef" };
            string str = (string)p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();

                db.Query("SELECT * FROM tblReferenceNumberCancelled WHERE fReferenceNumber='" + str + "'");
                if (db.Count == 0)
                {
                    db.Add(new object[] { DBNull.Value, str });
                    db.Commit();
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        }

        void pAddProfile(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "AddProfile" };
            ProfileInfo[] inp = (ProfileInfo[])p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                db.Query("SELECT * FROM tblProfile WHERE fSoldTo = '" + inp[0].name + "'");
                if (db.Count == 0)
                {
                    for (int i = 0; i < inp.Length; i++)
                    {
                        db.Query("SELECT * FROM tblProfile WHERE fRef = '" + inp[i].referenceNumber + "'");
                        if (db.Count == 0)
                        {
                            db.Query("SELECT * FROM tblProfile");

                            db.Add(new object[] { DBNull.Value, inp[i].referenceNumber, inp[i].name, inp[i].address, 
                        inp[i].contactNumber,inp[i].date, inp[i].status, DBNull.Value});
                            db.Commit(ConflictOption.CompareRowVersion);

                        }
                        else
                        {
                            proc.HasError = true;
                            proc.Msg = "Duplicate reference number exist.";
                        }
                    }
                }
                else
                {
                    proc.HasError = true;
                    proc.Msg = "Duplicate name exist.";
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        } // end pAddProfile

        void pViewProfile(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "ViewProfile" };
            SearchInfo keyword = (SearchInfo)p;
            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                db.Query("SELECT fRef, fSoldTo, fAddress, fTelNo, fMembershipDate, fStatus FROM tblProfile WHERE fSoldTo LIKE '" + keyword.keyword +
                    "%' OR fRef LIKE '" + keyword.keyword + "%' LIMIT " + keyword.start + ",50");
                db.Export(ref exportTable);
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        }

        void pGetRefNumber(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "GetRefNumber" };
            string inp = (string)p;
            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                db.Query("SELECT * FROM tblProfile WHERE fSoldTo = '" + inp + "'");
                if (db.Count > 0)
                {

                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = "Please Check Your Data...";
            }
            finally
            {
                err = proc;
            }
        }

        void pUpdateProfile(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "UpdateProfile" };
            ProfileInfo inp = (ProfileInfo)p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                db.Query("SELECT * FROM tblProfile WHERE fRef = '" + inp.SalesReferenceNumber + "'");
                if (db.Count == 1)
                {
                    DataRow dr = db.GetSchema();
                    dr["fRef"] = inp.SalesReferenceNumber;
                    dr["fSoldTo"] = inp.name;
                    dr["fAddress"] = inp.address;
                    dr["fTelNo"] = inp.contactNumber;
                    dr["fMembershipDate"] = inp.date;
                    dr["fStatus"] = inp.status;
                    db.Update(0, dr);
                    db.Commit(ConflictOption.CompareRowVersion);

                }
                db.Query("SELECT * FROM tblProfile WHERE fRef = '" + inp.ChargeReferenceNumber + "'");
                if (db.Count == 1)
                {
                    DataRow dr = db.GetSchema();
                    dr["fRef"] = inp.ChargeReferenceNumber;
                    dr["fSoldTo"] = inp.name;
                    dr["fAddress"] = inp.address;
                    dr["fTelNo"] = inp.contactNumber;
                    dr["fMembershipDate"] = inp.date;
                    dr["fStatus"] = inp.status;
                    db.Update(0, dr);
                    db.Commit(ConflictOption.CompareRowVersion);

                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        }
        //Async operations
        void GenericCB(IAsyncResult ar)
        {
            //Obtain the Delegate
            ThreadHandler ao = (ThreadHandler)((AsyncResult)ar).AsyncDelegate;
            //Prepare output
            object err;
            //Wrap-up the output
            ao.EndInvoke(out err, ar);
            UnityProcess er = (UnityProcess)err;
            if (!er.HasError)
            {
                OnProcessCompleted(er.ID, er.Msg);
            }
            else
            {
                OnProcessError(er.ID, er.Msg);
            }
        }
        public void AddProfile(ProfileInfo[] profileInfo)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pAddProfile);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(profileInfo, out er, ac, null);

        }
        public void AutoRef()
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pAutoRef);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(null, out er, ac, null);
        }
        public void GetCancelledRef()
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pGetCancelledRef);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(null, out er, ac, null);
        }
        public void SaveCancelledRef(string str)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pSaveCancelledRef);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(str, out er, ac, null);
        }
        public void ViewProfile(SearchInfo keyword)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pViewProfile);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(keyword, out er, ac, null);

        }
        public void UpdateProfile(ProfileInfo profileInfo)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pUpdateProfile);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(profileInfo, out er, ac, null);

        }
        //out
        public string SalesReferenceNumber
        {
            get { return salesReferenceNumber; }
        }
        public string ChargeReferenceNumber
        {
            get { return chargeReferenceNumber; }
        }
        //Events
        public event CoreHandler ProcessCompleted;
        public event CoreHandler ProcessError;
        protected virtual void OnProcessCompleted(string pCode, string msg)
        {
            if (ProcessCompleted != null) ProcessCompleted(pCode, msg);
        }
        protected virtual void OnProcessError(string pCode, string msg)
        {
            if (ProcessError != null) ProcessError(pCode, msg);
        }
    } // end class ProfileManager

    //--------------------------------
    //      class Charge Invoice
    //--------------------------------
    public class ChargeInvoiceManager : UnityProcessCall
    {
        // field
        OdbcAccess db = new OdbcAccess(CommonConnection.od);

        object[] bAutoSoldTo = new object[0];
        string[] bAutoInvoiceNumber = new string[0];
        string referenceNumber = "";

        public string count = "";

        public DataTable exportChargeInvoice = new DataTable();
        public DataTable exportChargePayments = new DataTable();

        // constructor
        public ChargeInvoiceManager() { db.Connect(); }

        //sync operation methods

        void pAddChargeInvoicePayment(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "ChargeInvoicePayment" };
            ChargeInvoiceInfo[] inp = (ChargeInvoiceInfo[])p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                for (int i = 0; i < inp.Length; i++)
                {
                    db.Query("SELECT * FROM tblSalesDetail WHERE fInvoice = '" + inp[i].InvoiceNumber + "'");
                    if (db.Count > 0)
                    {
                        db.Query("SELECT * FROM tblChargePayments");
                        db.Add(new object[] { DBNull.Value, inp[i].ReferenceNumber, inp[i].AccountName, inp[i].ORNumber, inp[i].BankName, 
                        inp[i].InvoiceNumber,inp[i].CheckNumber, inp[i].DateReceived, 
                        inp[i].DueDate, inp[i].Amount, inp[i].Mode, DBNull.Value});
                        db.Commit(ConflictOption.CompareRowVersion);

                        db.Query("SELECT * FROM tblChargeBalance WHERE fInvoice = '" + inp[i].InvoiceNumber + "' AND fStatus ='1'");
                        if (db.Count == 1)
                        {
                            db.SetField(0, "fStatus", "0");
                            string percentage = db.GetField(0, "fPercentage").ToString();
                            string terms = db.GetField(0, "fTerms").ToString();
                            string duedate = db.GetField(0, "fDueDates").ToString();
                            double balance = double.Parse(db.GetField(0, "fBalance").ToString());
                            db.Commit(ConflictOption.CompareRowVersion);
                            
                            //add new charge balance
                            DateTime oldDate, newDate, storeDate;
                            oldDate = DateTime.Parse(duedate);
                            newDate = DateTime.Parse(inp[i].DateReceived);
                            storeDate = oldDate;
                            if (newDate > oldDate)
                            {
                                int cnt = newDate.Subtract(oldDate).Days;
                                int termsVal = int.Parse(terms);
                                if (termsVal == 0) termsVal = 1;

                                if (cnt > termsVal)
                                {
                                    int l = cnt / termsVal;
                                    double per = (l * double.Parse(percentage)) / 100;
                                    balance = balance + (balance * per);

                                    int additionalDays = l * termsVal;
                                    storeDate = oldDate.AddDays(additionalDays);
                                }
                                else
                                {
                                    balance = balance + (balance * (double.Parse(percentage) / 100));
                                    storeDate = oldDate.AddDays(termsVal);
                                }
                            }

                            balance = balance - double.Parse(inp[i].Amount);
                            db.Query("SELECT * FROM tblChargeBalance");
                            db.Add(new object[] { DBNull.Value, inp[i].InvoiceNumber, Common.FormatCurrency(balance.ToString()), percentage, terms, storeDate.ToShortDateString(), inp[i].DateReceived, "1", DBNull.Value });
                            db.Commit(ConflictOption.CompareRowVersion);
                        }
                        else
                        {
                            proc.HasError = true;
                            proc.Msg = "Your Invoice Number is not yet recorded..." + inp[i].InvoiceNumber;
                        }
                    }
                    else
                    {
                        proc.HasError = true;
                        proc.Msg = "Your Invoice Number is not yet recorded..."+inp[i].InvoiceNumber;
                    }
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        } // end addPayment
        void pAutoSoldTo(object p, out object e)
        {
            UnityProcess proc = new UnityProcess() { ID = "AutoSoldTo" };
            string str = (string)p;
            try
            {

                object theLock = new object();
                lock (theLock)
                {
                    //if (db.State != ConnectionState.Connecting && db.State != ConnectionState.Open) db.Connect();    
                    OdbcAccess dbg = new OdbcAccess(CommonConnection.od);
                    dbg.Connect();
                    dbg.Query("SELECT DISTINCT fSoldTo FROM tblProfile WHERE fSoldTo LIKE '" + str + "%' ORDER BY fSoldTo ASC LIMIT 0, 5");
                    bAutoSoldTo = new object[dbg.Count];
                    dbg.Export(ref bAutoSoldTo, "fSoldTo");
                    //db.Disconnect();
                }
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = "Error getting soldto autofill.";
            }
            finally
            {
                e = proc;
            }
        } //end of autoSoldTo
        void pGetReferenceNumber(object p, out object e)
        {
            UnityProcess proc = new UnityProcess() { ID = "GetReferenceNumber" };
            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                string str = (string)p;
                db.Query("SELECT fRef FROM tblProfile WHERE fSoldTo = '" + str + "' AND fRef LIKE 'B%'");
                if (db.Count == 1)
                {
                    referenceNumber = db.GetField(0, "fRef").ToString();
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = "Error getting soldto autofill.";
            }
            finally
            {
                e = proc;
            }
        } //end ReferenceNumber
        void pLogBalance(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "LogBalance" };
            ChargeInvoiceInfo inp = (ChargeInvoiceInfo)p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();
                
                DateTime newDate, oldDate;
                oldDate = DateTime.Parse(inp.DateReceived);
                newDate = oldDate.AddDays(double.Parse(inp.Terms));
                double newBalance = double.Parse(inp.Balance) + (double.Parse(inp.Balance) * (double.Parse(inp.Percentage)/100));
                
                db.Query("SELECT * FROM tblChargeBalance");
                db.Add(new object[] { DBNull.Value, inp.InvoiceNumber, Common.FormatCurrency(newBalance), inp.Percentage, inp.Terms, newDate.ToShortDateString(), inp.DateReceived,"1", DBNull.Value });
                db.Commit(ConflictOption.CompareRowVersion);

                if (inp.Mode.Equals("New"))
                {
                    db.Query("SELECT * FROM tblPaymentTerms");
                    db.Add(new object[] { DBNull.Value, inp.InvoiceNumber, inp.Percentage, inp.Terms, DBNull.Value });
                    db.Commit(ConflictOption.CompareRowVersion);
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        } // end logBalance

        void pMigrate(object p, out object err)
        {
            UnityProcess proc = new UnityProcess() { ID = "Migrate" };
            //chargeMigrate[] inp = (chargeMigrate[])p;

            try
            {
                if (db.State == ConnectionState.Closed) db.Connect();

                db.Query("SELECT fInvoice, fQty, fUnitPrice FROM tblsalesitem");
                //struct for storing values
                
                //get all sales item
                salesItem[] si = new salesItem[db.Count];
                for (int i = 0; i < db.Count; i++)
                {
                    si[i].invoice = db.GetField(i, "fInvoice").ToString();
                    float qty = float.Parse(db.GetField(i, "fQty").ToString());
                    float unitPrice = float.Parse(db.GetField(i, "fUnitPrice").ToString());
                    si[i].amount = qty * unitPrice;
                }
                
                //get all payments
                db.Query("SELECT fInvoiceNumber, fAmount FROM tblChargePayments");
                paymentItems[] pi = new paymentItems[db.Count];
                for (int i = 0; i < db.Count; i++)
                {
                    pi[i].invoice = db.GetField(i, "fInvoiceNumber").ToString();
                    pi[i].amount = double.Parse(db.GetField(i, "fAmount").ToString());
                }

                //get all payment terms
                
                db.Query("SELECT * FROM tblPaymentTerms");
                paymentTerms[] pT = new paymentTerms[db.Count];
                for (int i = 0; i < db.Count; i++)
                {
                    pT[i].invoice = db.GetField(i, "fInvoice").ToString();
                    pT[i].terms = db.GetField(i, "fTerms").ToString();
                    pT[i].percentage = db.GetField(i, "fPercentage").ToString();
                }

                //get all salesdetail
                db.Query("SELECT * FROM tblSalesDetail WHERE fInvoiceType = 'Charged'");
                int recCount = db.Count;
                
                //storage
                string[] arrInvoiceNumber = new string[recCount];
                double[] amount = new double[recCount];
                DateTime[] rdate = new DateTime[recCount];
                double[] totalAmountPaid = new double[recCount];
                double[] totalBalance = new double[recCount];
                double[] terms = new double[recCount];
                double[] percentage = new double[recCount];

                for (int i = 0; i < arrInvoiceNumber.Length; i++)
                {
                    string invoice = db.GetField(i, "fInvoice").ToString();
                    
                    double amt = 0;
                    for (int j = 0; j < si.Length; j++)
                    {
                        if (invoice.Equals(si[j].invoice))
                        {
                            amt += si[j].amount;
                        }
                    }
                    

                    double tAmtPaid = 0;
                    for (int k = 0; k < pi.Length; k++)
                    {
                        if (invoice.Equals(pi[k].invoice))
                        {
                            tAmtPaid += pi[k].amount;
                        }
                    }
                    double t=0, per=0;
                    for (int l = 0; l < pT.Length; l++)
                    {
                        t = 0;
                        per = 0;
                        if(invoice.Equals(pT[l].invoice))
                        {
                            t = double.Parse(pT[l].terms);
                            per = double.Parse(pT[l].percentage);
                            l = pT.Length;
                        }
                    }

                    arrInvoiceNumber[i] = invoice;
                    amount[i] = amt;
                    rdate[i] = DateTime.Parse(db.GetField(i, "fDate").ToString());
                    totalAmountPaid[i] = tAmtPaid;
                    totalBalance[i] = amount[i] - totalAmountPaid[i];
                    terms[i] = t;
                    percentage[i] = per;
                }

                db.Query("SELECT * FROM tblChargeBalance");
                db.Delete(0, db.Count-1);
                db.Commit(ConflictOption.CompareRowVersion);

                //ADD ALL
                db.Query("SELECT * FROM tblChargeBalance");
                for (int i = 0; i < recCount; i++)
                {
                    db.Add(new object[] { DBNull.Value, arrInvoiceNumber[i], totalBalance[i], percentage[i],terms[i], 
                        rdate[i].AddDays(terms[i]).ToShortDateString(),rdate[i].ToShortDateString(), "1", DBNull.Value});
                    db.Commit(ConflictOption.CompareRowVersion);
                }
                db.Disconnect();
            }
            catch (Exception ex)
            {
                proc.HasError = true;
                proc.Msg = ex.Message;
            }
            finally
            {
                err = proc;
            }
        } // end logBalance
        

        public void AddChargeInvoicePayment(ChargeInvoiceInfo[] profileInfo)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pAddChargeInvoicePayment);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(profileInfo, out er, ac, null);

        }
        public void LogBalance(ChargeInvoiceInfo profileInfo)
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pLogBalance);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(profileInfo, out er, ac, null);

        }
        public void AutoSoldTo(string str)
        {
            ThreadHandler ao = new ThreadHandler(pAutoSoldTo);
            AsyncCallback ac = new AsyncCallback(GenericCB);
            object e;
            IAsyncResult ar = ao.BeginInvoke(str, out e, ac, null);
        }
        public void GetReferenceNumber(string str)
        {
            ThreadHandler ao = new ThreadHandler(pGetReferenceNumber);
            AsyncCallback ac = new AsyncCallback(GenericCB);
            object e;
            IAsyncResult ar = ao.BeginInvoke(str, out e, ac, null);
        }

        public void Migrate()
        {
            //Synchronous method to call.
            ThreadHandler ao = new ThreadHandler(pMigrate);
            //Async Callback
            AsyncCallback ac = new AsyncCallback(GenericCB);
            //Prepare out
            object er;
            //Call the Synchronous Method
            IAsyncResult ar = ao.BeginInvoke(null, out er, ac, null);

        }
       
        //out
        public object[] ListAutoSoldTo
        {
            get { return bAutoSoldTo; }
        }
        public string[] ListAutoInvoiceNumber
        {
            get { return bAutoInvoiceNumber; }
        }
        public string ReferenceNumber
        {
            get { return referenceNumber; }
        }
    }

} // end namespace DataManager
